package cn.com.dashihui.wx.controller;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.wx.common.Constants;
import cn.com.dashihui.wx.common.SysConfig;
import cn.com.dashihui.wx.common.UserCode;
import cn.com.dashihui.wx.dao.User;
import cn.com.dashihui.wx.dao.UserAddress;
import cn.com.dashihui.wx.dao.UserCollection;
import cn.com.dashihui.wx.interceptor.AuthLoginInterceptor;
import cn.com.dashihui.wx.interceptor.RefreshLoginInterceptor;
import cn.com.dashihui.wx.kit.MapKit;
import cn.com.dashihui.wx.kit.ValidateKit;
import cn.com.dashihui.wx.service.UserService;

/**
 * 用户操作对象<br/>包括登录、注册、个人信息管理、重置密码、收藏管理、收货地址管理操作
 */
@Before(AuthLoginInterceptor.class)
public class UserController extends BaseController{
	//使用Duang.duang进行封装，使普通类具有事务的功能
	private UserService service = Duang.duang(UserService.class);
	
	/**
	 * 个人中心首页<br/>
	 * 不限制登录状态
	 */
	@Clear(AuthLoginInterceptor.class)
	@Before(RefreshLoginInterceptor.class)
	public void index(){
		render("index.jsp");
	}
    
	/**
	 * 查询当前登录用户各状态信息<br/>
	 * 分别统计“收藏商品数量”、“待付款”、“待发货”、“待收货”、服务订单“待付款”、服务订单“待服务”六种状态的订单数量 
	 */
	public void state(){
		Record state = service.getUserState(getCurrentStoreid(),getCurrentUserid());
		renderSuccess(MapKit.one()
				.put("collected",state.get("state1"))
				.put("noPay",state.get("state2"))
				.put("noTake",state.get("state3"))
				.put("noEval",state.get("state4"))
				.put("serviceNoPay",state.get("state5"))
				.put("serviceNoService",state.get("state6")).getAttrs());
	}
    
	/**
	 * 跳转我的钱包<br/>
	 * 查询用户的实惠币金额
	 */
	@Before(RefreshLoginInterceptor.class)
	public void myWallet(){
		setAttr("currentUser", getCurrentUser());
		setAttr("invitedUserCount", service.findInviteUserCount(getCurrentUserid()));
		render("myWallet.jsp");
	}
	
	/**
	 * 跳转到什么是实惠币页面
	 */
	public void moneyIntro(){
		setAttr("currentUser", getCurrentUser());
		render("moneyIntro.jsp");
	}
	
	/**
	 * 跳转到我的实惠币页面
	 */
	public void myMoney(){
		setAttr("currentUser", getCurrentUser());
		render("myMoney.jsp");
	}
	
	/**
	 * 跳转到我的好友页面
	 */
	public void myFriends(){
		setAttr("currentUser", getCurrentUser());
		setAttr("invitedUserCount", service.findInviteUserCount(getCurrentUserid()));
		render("myFriends.jsp");
	}
	
	/**
	 * 会员奖励规则页面<br/>
	 * 不要求登录，任何人可看
	 */
	@Clear(AuthLoginInterceptor.class)
	@Before(RefreshLoginInterceptor.class)
	public void rule(){
		setAttr("currentUser", getCurrentUser());
		try {
			setAttr("level2Line", SysConfig.getLevel2Line());
		} catch (Exception e) {
			e.printStackTrace();
		}
		render("rule.jsp");
	}
	
	/**
	 * 会员分享页面<br/>
	 * 只有黄金会员可看，同时还要展示会员的邀请码
	 */
	public void share(){
		getJSApiParams(PropKit.get("constants.url_prev")+"/my/share");
		User currentUser = getCurrentUser();
		if(currentUser.getInt("level")==UserCode.UserLevel.LEVEL1){
			redirect("/index");
			return;
		}
		setAttr("currentUser", currentUser);
		render("share.jsp");
	}
	
	/**
	 * 我的门店<br/>
	 * 查看注册时绑定的店铺信息
	 */
	public void store(){
		setAttr("store", service.findStoreById(getCurrentStoreid()));
		render("store.jsp");
	}
	
	/**
	 * 解除当前用户的微信绑定<br/>
	 */
	public void unbind(){
		if(service.unbind(getCurrentUserid(), getCurrentWxUserid())){
			//解除绑定后，需要移除登录用户信息，使用户重新登录
	    	removeSessionAttr(Constants.USER);
			renderSuccess();
		}else{
			renderFailed();
		}
	}

	/**
	 * 更新用户个人信息，可单独修改任一字段或全部修改
	 * @param nickName 昵称
	 * @param sex 性别
	 * @param communityid 社区ID
	 * @param buildid 楼号ID
	 * @param unitid 单元号ID
	 * @param floorid 楼层ID
	 * @param roomid 房间号ID
	 */
	public void update(){
		String nickName = getPara("nickName");
		String sexStr = getPara("sex");
		String communityidStr = getPara("communityid");
		String buildidStr = getPara("buildid");
		String unitidStr = getPara("unitid");
		String flooridStr = getPara("floorid");
		String roomidStr = getPara("roomid");
		User user = getCurrentUser();boolean isNeedUpdate = false;
		if(!StrKit.isBlank(nickName)){
			user.set("nickName", nickName);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(sexStr)&&(sexStr.equals("1")||sexStr.equals("2"))){
			user.set("sex", sexStr);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(communityidStr)){
			user.set("communityid", communityidStr);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(buildidStr)){
			user.set("buildid", buildidStr);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(unitidStr)){
			user.set("unitid", unitidStr);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(flooridStr)){
			user.set("floorid", flooridStr);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(roomidStr)){
			user.set("roomid", roomidStr);isNeedUpdate = true;
		}
		if(isNeedUpdate){
			if(service.update(user)){
				renderSuccess();
			}else{
				renderFailed("更新信息失败");
			}
		}else{
			renderSuccess();
		}
	}
	
	/**
	 * 用户收藏指定商品
	 * @param goodsid 商品ID
	 */
	public void doCollect(){
		String goodsidStr = getPara("goodsid");
		int isSelf = getParaToInt("isSelf",0);
		if(StrKit.isBlank(goodsidStr)){
			renderFailed("参数GOODSID不能为空");
			return;
		}
		//收藏
		UserCollection c = service.doCollect(getCurrentStoreid(),isSelf,getCurrentUserid(),goodsidStr);
		renderSuccess(MapKit.one().put("isCancel", c.getInt("isCancel")).getAttrs());
	}
	
	/**
	 * 用户取消收藏指定商品
	 * @param goodsid 商品ID
	 */
	public void cancelCollect(){
		String goodsidsStr = getPara("goodsid");
		if(StrKit.isBlank(goodsidsStr)){
    		renderFailed("参数GOODSID不能为空");
    		return;
		}
		String[] goodsids;
		if(goodsidsStr.indexOf(",")>=1){
			goodsids = goodsidsStr.split(",");
		}else{
			goodsids = new String[]{goodsidsStr};
		}
		//批量取消收藏
		service.cancelCollect(getCurrentUserid(),goodsids);
		renderSuccess();
	}
	
	public void collection() {
		render("collection.jsp");
	}
	
	/**
	 * 分页查询用户收藏商品列表
	 * @param pageNum 页码
	 * @param pageSize 数量
	 */
	public void collectionList(){
		int pageNum = getParaToInt("pageNum",1);
		int pageSize = getParaToInt("pageSize",PropKit.getInt("constants.pageSize"));
		renderSuccess(service.findCollectionByPage(getCurrentStoreid(),getCurrentUserid(),pageNum, pageSize));
	}
	
	public void history() {
		render("history.jsp");
	}
	
	/**
	 * 收货地址
	 */
	public void address(){
		int from = getParaToInt("from");
		if(from == 1) {
			setSessionAttr("PAGE_FROM", "1");
		} else {
			removeSessionAttr("PAGE_FROM");
		}
		setAttr("addressList", service.findAddress(getCurrentUserid()));
		render("address.jsp");
	}
	
	/**
	 * 查询用户收货地址列表
	 */
	public void addressList(){
		renderSuccess(service.findAddressList(getCurrentUserid()));
	}
	
	/**
	 * 添加收货地址
	 */
	public void addrAdd(){
		render("addressAdd.jsp");
	}
	
	/**
	 * 增加收货地址
	 * @param linkName 收货人姓名
	 * @param sex 性别
	 * @param tel 联系电话，座机或手机号
	 * @param address 详细地址
	 * @param isDefault 是否设置为默认收货地址，1：是，0：否
	 */
	public void doAddrAdd(){
		String linkName = getPara("linkName");
		String sexStr = getPara("sex");
		String tel = getPara("tel");
		String addressStr = getPara("address");
		String isDefaultStr = getPara("isDefault","0");
		if(StrKit.isBlank(linkName)){
			renderResult(1,"参数LINKNAME不能为空");
			return;
		}else if(linkName.length()>20){
			renderResult(2,"参数LINKNAME过长");
			return;
		}else if(StrKit.isBlank(sexStr)){
			renderResult(3,"参数SEX不能为空");
			return;
		}else if(!sexStr.equals("1")&&!sexStr.equals("2")){
			renderResult(4,"参数SEX错误");
			return;
		}else if(StrKit.isBlank(tel)){
			renderResult(5,"参数TEL不能为空");
			return;
		}else if(!ValidateKit.Tel(tel)&&!ValidateKit.Mobile(tel)){
			renderResult(6,"参数TEL格式错误");
			return;
		}else if(StrKit.isBlank(addressStr)){
			renderResult(7,"参数ADDRESS不能为空");
			return;
		}else if(!StrKit.isBlank(isDefaultStr)&&!isDefaultStr.equals("1")&&!isDefaultStr.equals("0")){
			renderResult(8,"参数ISDEFAULT错误");
			return;
		}
		int userid = getCurrentUserid();
		UserAddress address = new UserAddress()
				.set("userid", userid)
				.set("linkName", linkName)
				.set("sex", sexStr)
				.set("tel", tel)
				.set("storeid",getCurrentStoreid())
				.set("address",addressStr);
		if(service.addAddress(userid,address,Integer.valueOf(isDefaultStr))){
			renderSuccess(address);
		}else{
			renderFailed("添加收货地址失败");
		}
	}
	
	/**
	 * 删除收货地址
	 * @param addressid 收货地址ID
	 */
	public void delAddress(){
		String addressid = getPara("addressid");
		if(StrKit.isBlank(addressid)){
			renderResult(1,"参数ADDRESSID不能为空");
    		return;
		}
		//批量删除收货地址
		service.delAddress(getCurrentUserid(),addressid);
		renderSuccess();
	}
	
	/**
	 * 编辑收货地址
	 */
	public void addrEdit(){
		setAttr("address", service.findAddressById(getParaToInt(0)));
		render("addressEdit.jsp");
	}
	
	/**
	 * 修改收货地址
	 * @param addressid 收货地址ID
	 * @param linkName 收货人姓名
	 * @param sex 性别
	 * @param tel 联系电话，座机或手机号
	 * @param address 详细地址
	 * @param isDefault 是否设置为默认收货地址，1：是，0：否
	 */
	public void updateAddress(){
		String addressidStr = getPara("addressid");
		String linkName = getPara("linkName");
		String sexStr = getPara("sex");
		String tel = getPara("tel");
		String addressStr = getPara("address");
		String isDefaultStr = getPara("isDefault","0");
		if(StrKit.isBlank(addressidStr)){
			renderResult(1,"参数ADDRESSID不能为空");
			return;
		}else if(StrKit.isBlank(linkName)){
			renderResult(2,"参数LINKNAME不能为空");
			return;
		}else if(linkName.length()>20){
			renderResult(3,"参数LINKNAME过长");
			return;
		}else if(StrKit.isBlank(sexStr)){
			renderResult(4,"参数SEX不能为空");
			return;
		}else if(!sexStr.equals("1")&&!sexStr.equals("2")){
			renderResult(5,"参数SEX错误");
			return;
		}else if(StrKit.isBlank(tel)){
			renderResult(6,"参数TEL不能为空");
			return;
		}else if(!ValidateKit.Tel(tel)&&!ValidateKit.Mobile(tel)){
			renderResult(7,"参数TEL格式错误");
			return;
		}else if(StrKit.isBlank(addressStr)){
			renderResult(8,"参数ADDRESS不能为空");
			return;
		}else if(!StrKit.isBlank(isDefaultStr)&&!isDefaultStr.equals("1")&&!isDefaultStr.equals("0")){
			renderResult(9,"参数ISDEFAULT错误");
			return;
		}
		int userid = getCurrentUserid();
		UserAddress address = new UserAddress()
				.set("id", Integer.valueOf(addressidStr))
				.set("userid", userid)
				.set("linkName", linkName)
				.set("sex", sexStr)
				.set("tel", tel)
				.set("storeid",getCurrentStoreid())
				.set("address",addressStr);
		if(service.updateAddress(userid,address,Integer.valueOf(isDefaultStr))){
			renderSuccess(address);
		}else{
			renderFailed("更新收货地址失败");
		}
	}
	
	/**
	 * 设置指定收货地址为默认
	 * @param addressid 收货地址ID
	 */
	public void setAddressDefault(){
		String addressidStr = getPara("addressid");
		if(StrKit.isBlank(addressidStr)){
			renderResult(1,"参数ADDRESSID不能为空");
			return;
		}else if(service.setAddressDefault(getCurrentUserid(),addressidStr,1)){
			renderSuccess();
			return;
		}
		renderFailed();
	}
	
	/**
	 * 查询用户消费记录
	 */
	public void expenseRecord(){
		int pageNum = getParaToInt("pageNum",1);
		int pageSize = getParaToInt("pageSize",PropKit.getInt("constants.pageSize"));
		int searchType = getParaToInt("searchType",0);
		renderSuccess(service.findUserExpenseRecord(pageNum, pageSize, getCurrentUser().getInt("id"),searchType));
	}
}
